﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Web.Caching;
using System.Web;

namespace Caching
{
    public class XmlDocumentCache : FileCacheHelpers
    {
        public string filename;
        CacheItemRemovedCallback onRemove = null;
        /// <summary>
        /// 文件名称
        /// </summary>
        public override string FileName
        {
            get;
            set;
        }
        public override string CacheKey { get; set; }
        /// <summary>
        /// XmlPath查询表达式
        /// </summary>
        /// 
        public string XmlPathExpression { get; set; }

        /// <summary>
        /// 定义缓存移除回调函数
        /// </summary>
        /// <param name="k">缓存key</param>
        /// <param name="v">缓存值</param>
        /// <param name="r">移除原因</param>
        public void RemovedCallback(String k, Object v, CacheItemRemovedReason r)
        {
            AddFileCache();
        }

        public XmlDocumentCache()
        {
            onRemove = new CacheItemRemovedCallback(RemovedCallback);
        }

        public override bool AddFileCache()
        {

            bool flag = false;
            if (HttpRuntime.Cache[this.CacheKey] == null)
            {
                if (string.IsNullOrEmpty(this.FileName))
                    throw new Exception("文件名不能为空!");
                else
                {
                    if (File.Exists(this.FileName))
                    {
                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.Load(this.FileName);
                        if (xmlDoc != null)
                        {
                            CacheDependency Dependency = new CacheDependency(this.FileName);
                            HttpRuntime.Cache.Add(this.CacheKey, xmlDoc, Dependency, DateTime.Now.AddYears(1), Cache.NoSlidingExpiration, CacheItemPriority.High, onRemove);
                                flag = true;
                            
                        }
                    }
                    else
                    {
                        throw new Exception("文件不存在");
                    }
                }
            }

            return flag;

        }
        public override bool RemoveFileCache()
        {
            throw new NotImplementedException();
        }
    }
}
